package dynamic.thread.pool.test.init;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ThreadPoolRunner implements ApplicationRunner {
    @Autowired
    private ThreadPoolExecutor testThreadPool;
    @Autowired
    private ThreadPoolTaskExecutor taskThreadPool;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        while (true){
            // 创建一个随机时间生成器
            Random random = new Random();
            // 随机休眠时间，用于模拟任务执行时间
            int randomNumber = random.nextInt(101) + 200; //生成200到300之间的随机数

            // 提交任务到线程池
            testThreadPool.execute(() -> {
                try {
                    // 模拟任务执行
                    TimeUnit.MILLISECONDS.sleep(randomNumber);
                    log.info("[testThreadPool]Task执行时间：{} ms.", randomNumber);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            // 提交任务到线程池
            taskThreadPool.submit(() -> {
                try {
                    // 模拟任务执行
                    TimeUnit.MILLISECONDS.sleep(randomNumber);
                    log.info("[taskPool线程池]Task执行时间：{} ms.", randomNumber);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            TimeUnit.MILLISECONDS.sleep(10);
        }
    }
}
